﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlUser : System.Web.UI.UserControl
{
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    ClassExecute.ClassExecute dt;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            //nằm trong thread
            ThreadStart ths1 = new ThreadStart(GetBrandList);
            ThreadStart ths2 = new ThreadStart(GetUserType);
            ThreadStart ths3 = new ThreadStart(BindUserType);
            Thread th1 = new Thread(ths1);
            Thread th2 = new Thread(ths2);
            Thread th3 = new Thread(ths3);

            th1.Start();
            th2.Start();
            th3.Start();

            th1.Join();
            th2.Join();
            th3.Join();
            ClearAdd();
            //nằm trong thread
        }        
    }

    void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtUserName.Text = "";
        txtName.Text = "";
        txtUserName.ReadOnly = false;
        
        ViewState["flag"] = true;
        txtUserName.Focus();

        btnSave.Text = "Lưu";
        lblMsg.Text = "";
        lblMsg.Visible = false;
    }

    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
    }



    private void BindUserType()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "TTr_getUserTypeList", CommandType.StoredProcedure);
         dt.BindDropDownList(db, ddlUserType, "TypeID", "TypeName");
    }
    //public void BindDropDownList(DataTable db, DropDownList NameDropDownList, string DataValue, string DataText)
    //{
    //    NameDropDownList.DataSource = db;
    //    NameDropDownList.DataTextField = DataText;
    //    NameDropDownList.DataValueField = DataValue;
    //    NameDropDownList.DataBind();
    //    NameDropDownList.Items.Insert(0, "");
    //}
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGridSearch();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();        
        try
        {
            if ((bool)ViewState["flag"])
            {
                bool rel = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "D_Users_Insert", ref error,
                    new SqlParameter("@UserName", txtUserName.Text.Trim()),
                    new SqlParameter("@UserDescription", txtName.Text),
                    new SqlParameter("@Password", dt.GetMd5Sum(txtPass.Text)),
                    new SqlParameter("@Sitecode", ddlChiNhanh.SelectedValue.ToString()),
                    new SqlParameter("@UserType", ddlThuocNhom.SelectedValue.ToString()),
                    new SqlParameter("@Active", chbCanLogin.Checked),
                    new SqlParameter("@PassHint", txtPass.Text));
                if (rel)
                {
                    ClearAdd();
                    lblMsg.Text = "Thêm mới người dùng thành công";
                    lblMsg.Visible = true;
                }
                else
                {
                    lblMsg.Text = "Thêm mới người dùng thất bại";
                    lblMsg.Visible = true;
                }
            }
            else
            {
                int i = 0;
                i = dt.ExecuteSQl_int(str, "k_updateUserSystem", CommandType.StoredProcedure, ref error,
                   new SqlParameter("@UserName", txtUserName.Text),
                   new SqlParameter("@UserDescription", txtName.Text),
                   new SqlParameter("@Password", dt.GetMd5Sum(txtPass.Text)),
                   new SqlParameter("@Sitecode", ddlChiNhanh.SelectedValue.ToString()),
                   new SqlParameter("@UserType", ddlThuocNhom.SelectedValue.ToString()),
                   new SqlParameter("@Active", chbCanLogin.Checked),
                   new SqlParameter("@PassHint", txtPass.Text));
                if (i == 1)
                {
                    lblMsg.Text = "Cập nhật thông tin người dùng thành công";
                    lblMsg.Visible = true;
                }
                else
                {
                    lblMsg.Text = "Cập nhật thông tin người dùng thất bại";
                    lblMsg.Visible = true;
                }
                
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    private bool IsExsitUser()
    {
        try
        {
            dt = new ClassExecute.ClassExecute();
            //int i = dt.ExecuteSQl_int(str, "D_UserSystem_IsExsit", CommandType.StoredProcedure, ref error,
            //       new SqlParameter("@UserName", txtUserName.Text));
            int rel = dt.ExecuteSQl_int(str, "D_UserSystem_IsExsit", CommandType.StoredProcedure, ref error,
                   new SqlParameter("@UserName", txtUserName.Text));
            if (rel>0)
            {
                return true; 
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

    void GetBrandList()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getBrandList", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlChiNhanh, "Sitecode", "sitename");

    }
    void GetUserType()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getUserTypeList", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlThuocNhom, "TypeID", "TypeName");
    }
    void BindGridSearch()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "[K_FindUserSystem]", CommandType.StoredProcedure,
            new SqlParameter("@parameter", txtSearch.Text),
            new SqlParameter("@TypeID", ddlUserType.SelectedValue));

        if (db.Rows.Count > 0)
        {
            grvUser.DataSource = db;
        }
        else
        {
            grvUser.DataSource = null;
        }
        grvUser.DataBind();

    }
    protected void grvUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvUser.PageIndex = e.NewPageIndex;
        BindGridSearch();

    }
    protected void grvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblUser = (Label)grv.FindControl("lblUser");
                DataTable db = dt.Get_Data_DataTable(str, ref error, "[K_GetUser]", CommandType.StoredProcedure,
                    new SqlParameter("@UserName", lblUser.Text));

                txtName.Text = db.Rows[0]["UserDescription"].ToString();
                txtUserName.Text = db.Rows[0]["UserName"].ToString();
                chbCanLogin.Checked = bool.Parse(db.Rows[0]["Active"].ToString());
                txtPass.Text = db.Rows[0]["PassHint"].ToString();
                try
                {
                    ddlChiNhanh.SelectedValue = db.Rows[0]["Sitecode"].ToString();
                }
                catch
                {
                }
                try
                {
                    ddlThuocNhom.SelectedValue = db.Rows[0]["UserType"].ToString();
                }
                catch
                {
                }

                txtUserName.ReadOnly = true;
                ViewState["flag"] = false;
                btnSave.Text = "Cập nhật";
                lblMsg.Text = "";
                lblMsg.Visible = false;
                grvUser.DataSource = null;
                grvUser.DataBind();

                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    
}